import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { EzFormComponent } from '../ez-form';
import { EzFormControlComponent } from '../ez-form-control';
import { EzFormGroupComponent } from '../ez-form-group';
import { EzFormItemComponent } from '../ez-form-item';
import { EzRadio } from './ez-radio';
import { EzRadioConfiguration, EzRadioOptions } from './ez-radio.configuration';

@Component({
  selector: 'ez-radio',
  templateUrl: './ez-radio.component.html',
  styleUrls: ['./ez-radio.component.less'],
  providers: [{ provide: EzFormControlComponent, useExisting: EzRadioComponent }],
})
export class EzRadioComponent extends EzFormControlComponent<EzRadioConfiguration, any>
  implements EzRadio, OnInit, OnDestroy {
  loading = false;

  options: EzRadioOptions = [];

  constructor(
    protected ezForm: EzFormComponent,
    protected ezFormGroup: EzFormGroupComponent,
    protected ezFormItem: EzFormItemComponent
  ) {
    super(ezForm, ezFormGroup, ezFormItem);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.setOptions(
      this.ezFormControlConfiguration.options instanceof Function
        ? this.ezFormControlConfiguration.options(this, this.ezFormGroup, this.ezForm)
        : this.ezFormControlConfiguration.options
    );
  }

  ngOnDestroy(): void {
    super.ngOnDestroy();
  }

  checkConfiguration(configuration: EzRadioConfiguration): void {}

  setOptions(options: EzRadioOptions | Observable<EzRadioOptions> = []) {
    if (options instanceof Observable) {
      options.subscribe(
        ops => {
          this.loading = false;
          this.options = ops;
        },
        e => {
          this.loading = false;
          console.error(e);
        }
      );
    } else {
      this.options = options;
    }
  }

  optionsDisplayInline(): boolean {
    return (
      this.ezForm.ezFormConfiguration.layout === 'inline' ||
      !(
        this.ezFormControlConfiguration.span === 24 ||
        this.ezForm.ezFormConfiguration.cols === 1 ||
        !this.ezForm.ezFormConfiguration.cols
      )
    );
  }
}
